-- ScheduleM
-- Created by panyl Mar/21/2016
-- 定时器模块

module("ScheduleM", package.seeall);

local schedules = {};

local schedulerIndex = 0;

local paused = false;

-- 初始化
function init()
    schedules = {};
end

-- 创建一个定时事件
function createScheme(eventName, func, interval, REPEAT)
    assert(type(func) == "function");
    assert(type(interval) == "number");

    -- 注册一个事件
    schedules[eventName] = {
        ["func"]      = func,
        ["nextTime"]  = socket.gettime() + interval,
        ["interval"]  = interval,
        ["repeat"]    = REPEAT or false,
    };
end

-- 删除事件
function deleteScheme(eventName)
    if not schedules[eventName] then
        return;
    end

    schedules[eventName] = nil;
end

function update()
    if paused then
        return;
    end

    local stopList = {};

    for eventName, data in pairs(schedules) do
        if data["stop"] then
            -- 后面处理
            table.insert(stopList, eventName);
        elseif data["nextTime"] <= socket.gettime() then
            -- 时间到
            catch(data["func"]);

            -- 下一次时间
            data["nextTime"] = socket.gettime() + data["interval"];

            -- 如果不是重复的事件，执行一次就行了
            if not data["repeat"] then
                table.insert(stopList, eventName);
            end
        end
    end

    for _, eventName in pairs(stopList) do
        schedules[eventName] = nil;
    end
end

-- 获取所有的事件
function fetchAllEvents()
    return schedules;
end

-- 获取事件列表
function getEventList()
    return table.keys(schedules);
end

-- 判断否个事件是否存活中
function isSchemeAlive(eventName)
    local data = schedules[eventName];
    if not data then
        return false;
    end

    -- 被暂停了
    if data["stop"] then
        return false;
    end

    return true;
end

-- 暂停
function pause()
    paused = true;
end

-- 继续
function resume()
    paused = false;
end